package logger

import (
	"fmt"
	"goGameWebServer/internal/common/config"
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

type Logger struct {
	logger *zap.Logger
}

func NewLogger(op *config.ServerOptions) *Logger {
	newLogger := new(Logger)
	atomicLevel := zap.NewAtomicLevel()
	switch op.LogOptions.LogLevel {
	case "Debug":
		atomicLevel.SetLevel(zap.DebugLevel)
	case "Info":
		atomicLevel.SetLevel(zap.InfoLevel)
	case "Warn":
		atomicLevel.SetLevel(zap.WarnLevel)
	case "Error":
		atomicLevel.SetLevel(zap.ErrorLevel)
	case "Fatal":
		atomicLevel.SetLevel(zap.FatalLevel)
	default:
		atomicLevel.SetLevel(zap.InfoLevel)
	}
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "line",
		MessageKey:     "msg",
		FunctionKey:    "func",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.CapitalColorLevelEncoder,
		EncodeTime:     zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05"),
		EncodeDuration: zapcore.SecondsDurationEncoder,
		//EncodeCaller:   zapcore.FullCallerEncoder,
		EncodeName: zapcore.FullNameEncoder,
	}
	writer := &lumberjack.Logger{
		Filename:   fmt.Sprintf("%s/phoenix_log.log", op.LogOptions.LogPath),
		MaxSize:    100,
		MaxAge:     30,
		MaxBackups: 10,
		LocalTime:  true,
		Compress:   false,
	}
	zapCore := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfig),
		zapcore.NewMultiWriteSyncer(zapcore.AddSync(writer), zapcore.AddSync(os.Stdout)),
		atomicLevel,
	)
	//phoenixLogger.logger = zap.New(zapCore, zap.AddCaller())
	newLogger.logger = zap.New(zapCore)
	logger = newLogger
	return newLogger
}

func (lg *Logger) Debug(msg string, fields ...zapcore.Field) {
	lg.logger.Debug(msg, fields...)
}

func (lg *Logger) Info(msg string, fields ...zapcore.Field) {
	lg.logger.Info(msg, fields...)
}

func (lg *Logger) Warn(msg string, fields ...zapcore.Field) {
	lg.logger.Warn(msg, fields...)
}

func (lg *Logger) Error(msg string, fields ...zapcore.Field) {
	lg.logger.Error(msg, fields...)
}

func (lg *Logger) Fatal(msg string, fields ...zapcore.Field) {
	lg.logger.Fatal(msg, fields...)
}

func (lg *Logger) Debugf(template string, args ...interface{}) {
	lg.logger.Sugar().Debugf(template, args...)
}

func (lg *Logger) Infof(template string, args ...interface{}) {
	lg.logger.Sugar().Infof(template, args...)
}

func (lg *Logger) Warnf(template string, args ...interface{}) {
	lg.logger.Sugar().Warnf(template, args...)
}

func (lg *Logger) Errorf(template string, args ...interface{}) {
	lg.logger.Sugar().Errorf(template, args...)
}

func (lg *Logger) Fatalf(template string, args ...interface{}) {
	lg.logger.Sugar().Fatalf(template, args...)
}

// 实现一个单例
var logger *Logger

func LoggerIns() *Logger {
	return logger
}
